<?php


namespace app\common\model\member\money;

use Exception;
use mb\helper\Collection;
use think\Db;

class Log
{
    public static $typeTitle = [
        // 'orderAdd' => '下单',
        // 'orderPush' => '返奖',

        // 'recharge' => '充值',
        // 'rechargeControl' => '后台充值',

        // 'cjRecharge' => '彩金充值',
        // 'error' => '异常扣除',

        // 'withdrawal' => '提现申请',
        // 'withdrawalError' => '提现申请驳回',
        // 'withdrawalControl' => '后台提现',

        // 'commission1' => '一级返佣',
        // 'commission2' => '二级返佣',
        // 'commission3' => '三级返佣',

        // 'water1' => '一级流水佣金',
        // 'water2' => '二级流水佣金',
        // 'water3' => '三级流水佣金',

        // 'sendWater' => '手动发放流水',
        //       'agPush' => '真人兑出',
        // 'agAdd' => '真人兑入',
        
        'orderAdd' => 'đặt hàng',
         'orderPush' => 'phần thưởng',

         'nạp năng lượng' => 'nạp năng lượng',
         'rechargeControl' => 'nạp lại trong nền',

         'cjRecharge' => 'tiền thưởng nạp tiền',
         'lỗi' => 'khấu trừ bất thường',

         'rút tiền' => 'đơn xin rút tiền',
         'withdrawalError' => 'đơn xin rút tiền bị từ chối',
         'withdrawalControl' => 'rút tiền trong nền',

         'commission1' => 'Giảm giá cấp 1',
         'hoa hồng2' => 'chiết khấu phụ',
         'hoa hồng3' => 'Giảm giá cấp ba',

         'water1' => 'Hoa hồng doanh thu cấp 1',
         'water2' => 'hoa hồng doanh thu phụ',
         'water3' => 'Hoa hồng doanh thu ba cấp',

         'sendWater' => 'Cấp nước thủ công',
               'agPush' => 'người thật rút tiền',
         'agAdd' => 'Tiền gửi của người thật',
    ];
    protected static $table = 'member_money_logs';

    /**
     * @param array $row
     * @return bool|int|string
     */
    public static function add(array $row,$connect = null)
    {
        $newRow = Collection::elements([
            'memberId',
            'targetId',
            'type',
            'afterMoney',
            'ghost',
            'money',
            'msg',
            'adminId',
            'existence',
        ], $row);
        $newRow['timeCreated'] = time();
        $newRow = Collection::keyStyle($newRow, Collection::NAME_STYLE_C);
        try {
            if (empty($connect)) {
                $connect = Db::connect();
            }
            return $connect->table(self::$table)
                ->insertGetId($newRow);
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
    }

    /**
     * @param $filter
     * @return array|Error
     */
    public static function fetch($filter)
    {
        $where = self::parseFilters($filter);
        try {
            $row = Db::table(self::$table)
                ->where($where)
                ->find();
            if (!empty($row)) {
                $row['time_created'] *= 1000;
                return Collection::keyStyle($row, Collection::NAME_STYLE_JAVA);
            }
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
        return [];
    }

    /**
     * @param $filter
     * @return bool|Error
     */
    public static function remove($filter)
    {
        $where = self::parseFilters($filter);
        try {
            $offect = Db::table(self::$table)
                ->where($where)
                ->delete();
            if ($offect === 1) {
                return true;
            }
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
        return $offect;
    }

    /**
     * @param $filter
     * @param $newState
     * @return bool|Error
     */
    public static function update($filter, $newState)
    {
        $where = self::parseFilters($filter);
        try {
            $offect = Db::table(self::$table)
                ->where($where)
                ->update($newState);
            if ($offect === 1) {
                return true;
            }
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
        return $offect;
    }

    /**
     * @param $filter
     * @return array
     */
    public static function parseFilters($filter)
    {
        $where = [];
        if (is_array($filter)) {
            if (!empty($filter['id'])) {
                $where[] = ['id', '=', $filter['id']];
            }
            if (!empty($filter['memberId'])) {
                $where[] = ['member_id', '=', $filter['memberId']];
            }
            if (!empty($filter['targetId']) && !empty($filter['type'])) {
                $where[] = ['target_id', '=', $filter['targetId']];
                $where[] = ['type', '=', $filter['type']];
            }
            if (empty($where)) {
                throw error(-10, '参数错误必须指定id');
            }
        } else {
            $where[] = ['id', '=', intval($filter)];
        }
        return $where;
    }

    /**
     * @param array $filters
     * @param int $pIndex
     * @param int $pSize
     * @param int $total
     * @return array|Error
     */
    public static function search(array $filters, int $pIndex = 0, int $pSize = 10, int &$total = 0)
    {
        $where = self::parseSearchFilters($filters);
        try {
            if (!empty($pIndex)) {
                $total = Db::table(self::$table)
                    ->where($where)
                    ->count();
            }
            $query = Db::table(self::$table)
                ->where($where);
            if (!empty($pIndex)) {
                $query->page($pIndex, $pSize);
            }
            if (!empty($filters['order'])) {
                $query->order($filters['order']);
            }
            $dataSet = $query->select();
            if (!$dataSet->isEmpty()) {
                return $dataSet->map(
                    function ($row) {
                        $row['typeTitle'] = empty(self::$typeTitle[$row['type']])?'':self::$typeTitle[$row['type']];
                        $row['time_created'] *= 1000;
                        $row = Collection::keyStyle($row, Collection::NAME_STYLE_JAVA);
                        return $row;
                    }
                )->toArray();
            }

        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
        return [];
    }
    public static function sumFiled($filters,$filed)
    {
        $where = self::parseSearchFilters($filters);
        try {
            return Db::table(self::$table)->where($where)->sum($filed);
        }catch (Exception $e) {
            return 0;
        }
    }
    public static function parseSearchFilters($filters)
    {
        $where = [];
        if (!empty($filters['timeCreatedStart'])) {
            $where[] = ['time_created', '>=', $filters['timeCreatedStart']];
        }
        if (!empty($filters['timeCreatedEnd'])) {
            $where[] = ['time_created', '<=', $filters['timeCreatedEnd']];
        }
        if (!empty($filters['type'])) {
            $where[] = ['type','=',$filters['type']];
        }
        if (!empty($filters['types'])) {
            $where[] = ['type','in',$filters['types']];
        }
        if (!empty($filters['memberId'])) {
            $where[] = ['member_id','=',$filters['memberId']];
        }
        if (!empty($filters['existence'])) {
            $where[] = ['existence', '=', $filters['existence']];
        }
        return $where;
    }
}